package com.etop.jansing.service;

import com.etop.jansing.dao.RoleDao;
import com.etop.jansing.dao.UserDao;
import com.etop.jansing.entities.User;
import com.etop.jansing.util.CommonUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by jansing on 2015/10/25.
 */
@Service
public class UserService extends BaseService{
    @Resource
    private UserDao userDao;
    @Resource
    private RoleDao roleDao;

    public User login(User user) {
        log.info("-->用户登陆：username=["+user.getUsername()+"]");
        User tempUser = userDao.getByUsername(user.getUsername());
        if (tempUser == null) {
            log.error("-->用户名或密码错误：username=[" + user.getUsername()+"]");
            return null;
        }
        if (tempUser.getPassword().equals(user.getPassword().trim())) {
            return tempUser;
        } else {
            log.error("-->用户名或密码错误：username=[" + user.getUsername()+"]");
        }
        return null;
    }

    public List<User> getUserList() {
        log.info("-->获取用户列表");
        return userDao.list();
    }

    public User getById(long id) {
        log.info("-->获取id=["+id+"]的用户");
        User user = userDao.get(id);
        if(user==null){
            log.warn("-->id=["+id+"]的用户不存在");
        }
        return user;
    }

    public void saveOrUpdate(User user, String[] rids) {
        //先去掉所有已有的角色，再加上选择了的角色
        User tempUser = user;
        if (user.getId() != null && user.getId() > 0) {
            tempUser = userDao.get(user.getId());
            tempUser.getRoleList().clear();
        }
        if (rids != null && rids.length != 0) {
            tempUser.getRoleList().addAll(roleDao.getByIds(CommonUtils.parseIds(rids)));
        }
        if (tempUser.getId() != null && tempUser.getId() > 0) {
            log.info("-->更新用户");
            userDao.update(tempUser);
        } else {
            log.info("-->保存用户");
            userDao.save(tempUser);
        }
    }

    /**
     * 删除用户，先删除用户角色关联表相应的记录
     *
     * @param id
     */
    public void delete(long id) {
        log.info("-->删除id=["+id+"]的用户");
        User user = userDao.get(id);
        if (user == null) {
            log.warn("-->id=["+id+"]的用户不存在");
            return;
        }
        user.getRoleList().clear();
        userDao.delete(user);
    }

}
